package cn.huayu.edu.session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class IndexServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		System.out.println(request.getRemoteHost());
		// 解决乱码问题
		response.setContentType("text/html;charset=utf-8");
		// 创建或者获取保存用户信息的Session对象
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.getWriter().print("<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<center>您还没有登录，请<a href='"+request.getContextPath()+"/jsp/session/login.jsp'>登录</a></center>");
		} else {
			response.getWriter().print("<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<br/>\r\n"
					+ "<center>您已登录，欢迎你，" + user.getUsername() + "！");
			response.getWriter().print("<a href='"+request.getContextPath()+"/LogoutServlet'>退出</a></center>");
			// 创建Cookie存放Session的标识号
			Cookie cookie = new Cookie("JSESSIONID", session.getId());
			cookie.setMaxAge(60 * 30);

			cookie.setPath("/web");
			response.addCookie(cookie);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
